import requests
from django.shortcuts import render
from QQLoginTool.QQtool import OAuthQQ
from rest_framework.generics import UpdateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from django.conf import settings
from rest_framework_jwt.settings import api_settings

# from .wb_oauth import OAuthWB
from meiduo.settings.dev import Weibo_CLIENT_ID, Weibo_CLIENT_SECRET, Weibo_REDIRECT_URI
from oauth.models import OauthQQUser,OAuthSinaUser
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from oauth.serializers import OauthViewSerializer, OauthWeiboSerializers
from users.serializers import UserUpdateSerializer
from users.utils import merge_cart_cookie_to_redis

from oauth.sinaWB.sinaweibopy3 import APIClient
import json
import urllib
import re


class OauthQQloginView(APIView):

    def get(self, request):
        state = request.query_params.get('next', None)
        if not state:
            state = settings.QQ_STATE

        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        login_url = qq.get_qq_url()

        return Response({'login_url': login_url})


class OauthView(APIView):

    def get(self, request):
        code = request.query_params.get('code', None)

        if not code:
            return Response({'error': '没得code值哦你个哈皮'})

        state = '/'
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        access_token = qq.get_access_token(code)

        openid = qq.get_open_id(access_token)

        try:
            qq_user = OauthQQUser.objects.get(openid=openid)
        except:
            tjs = TJS(settings.SECRET_KEY, 300)
            openid = tjs.dumps({'openid': openid}).decode()
            return Response({'access_token': openid})
        else:
            user = qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)  # 载荷
            token = jwt_encode_handler(payload)  # token

            user.token = token
            response = Response(
                {
                    'token': token,
                    'username': user.username,
                    'user_id': user.id
                }
            )
            # 合并购物车
            response = merge_cart_cookie_to_redis(request, user, response)

            return response

    def post(self, request):
        data = request.data
        ser = OauthViewSerializer(data=data)
        ser.is_valid()
        print(ser.errors)
        ser.save()
        return Response(ser.data)



class OauthWeibologinView(APIView):
    """
        构建微博登录跳转链接
    """
    def get(self, request):
        # 1、创建微博对象
        weibo = APIClient(app_key=Weibo_CLIENT_ID, app_secret=Weibo_CLIENT_SECRET, redirect_uri=
        Weibo_REDIRECT_URI)
        # 2、构建跳转连接
        login_url = weibo.get_authorize_url()
        # 3、返回跳转连接
        return Response({'login_weibo_url': login_url})

class OauthweiboView(APIView):
    def get(self, request):
        # 1、获取code值
        code = request.query_params.get('code', None)
        # 2、判断code是否传递过来
        if not code:
            return Response({'error': '缺少code值'}, status=400)
        # 3、通过code值获取access_token值
        weibo = APIClient(app_key=Weibo_CLIENT_ID, app_secret=Weibo_CLIENT_SECRET, redirect_uri=
        Weibo_REDIRECT_URI)
        access_token=weibo.request_access_token(code)

        # 5、判断access_token是否绑定过美多用户
        try:
            weibo_user = OAuthSinaUser.objects.get(access_token=access_token["access_token"])
        except:
            # 6、未绑定，进入到绑定页面完成绑定
            tjs = TJS(settings.SECRET_KEY, 300)
            # 给access_token加密(decode二进制转换成字符串)
            access_token = tjs.dumps({'access_token': access_token["access_token"]}).decode()
            return Response({'access_token': access_token})
        else:
            # 7、绑定过，则登录成功
            # 生成JWT-token值
            user = weibo_user.user
            print({'user':user})
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)  # 生成载荷部分
            token = jwt_encode_handler(payload)  # 生成token
            return Response(
                {
                    'token': token,
                    'username': user.username,
                    'user_id': user.id
                }
            )

    def post(self, request):
        # 1、获取前端数据
        data = request.data
        # 2、验证数据
        ser = OauthWeiboSerializers(data=data)
        ser.is_valid()
        print(ser.errors)
        # 3、绑定保存数据
        ser.save()
        # 4、返回结果
        return Response(ser.data)






